package com.cuz.for2024;

import java.lang.reflect.Array;
import java.util.Arrays;

public class T34 {
    public static void main(String[] args) {
        int[] ints = new T34().searchRange(new int[]{2, 2}, 3);
        System.out.println(Arrays.toString(ints));
    }

    public int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[]{-1, -1};
        }
        if (nums.length == 1) {
            return nums[0] == target ? new int[]{0, -1} : new int[]{-1, -1};
        }
        int first = bSearch(nums, 0, target, nums.length - 1, true);
        if (first == -1) {
            return new int[]{-1, -1};
        }
        int second = bSearch(nums, first, target, nums.length - 1, false);

        return new int[]{first, second};
    }

    private int bSearch(int[] nums, int start, int target, int end, boolean low) {
        while (start <= end) {
            int mid = (end - start) / 2 + start;
            int midValue = nums[mid];
            if (low) {
                if (midValue >= target) {
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            } else {
                if (midValue <= target) {
                    start = mid + 1;
                } else {
                    end = mid - 1;
                }
            }
        }
        if (low) {
            return start < nums.length && nums[start] == target ? start : -1;
        }
        return end >= 0 && nums[end] == target ? end : -1;
    }
}
